#include <iostream>
#include <unistd.h>
#include <pthread.h>

int cnt = 0;
pthread_mutex_t mutexA = PTHREAD_MUTEX_INITIALIZER;
pthread_mutex_t mutexB = PTHREAD_MUTEX_INITIALIZER;

void* startRoutineA(void* args) {
    while (true) {
        pthread_mutex_lock(&mutexA);
        sleep(1);
        pthread_mutex_lock(&mutexB);
        cnt++;
        printf("cnt: %d", cnt);
        pthread_mutex_unlock(&mutexA);
        pthread_mutex_unlock(&mutexB);
    }

    return nullptr;
}

void* startRoutineB(void* args) {
    while (true) {
        pthread_mutex_lock(&mutexB);
        sleep(1);
        pthread_mutex_lock(&mutexA);
        cnt++;
        printf("cnt: %d", cnt);
        pthread_mutex_unlock(&mutexB);
        pthread_mutex_unlock(&mutexA);
    }

    return nullptr;
}

int main() {
    pthread_mutex_init(&mutexA, nullptr);
    pthread_mutex_init(&mutexB, nullptr);

    pthread_t tidA, tidB;

    pthread_create(&tidA, nullptr, startRoutineA, (void*)"threadA");
    pthread_create(&tidB, nullptr, startRoutineB, (void*)"threadB");

    pthread_join(tidA, nullptr);
    pthread_join(tidB, nullptr);

    return 0;
}
